<template>
  <el-dialog
    v-model="dialogFormCoveVisible"
    :title="`${titleActive}品牌`"
    width="800"
  >
    <el-form
      ref="formRef"
      :rules="rules"
      :model="trademarkParams"
      style="width: 80%"
    >
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input
          v-model="trademarkParams.tmName"
          autocomplete="off"
          placeholder="请输入品牌名称"
        />
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <!-- 上传文件组件
         action:将文件上传的服务器地址
        
        -->
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="trademarkParams.logoUrl"
            :src="trademarkParams.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <upload-filled />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <!-- 具名插槽 -->
    <template #footer>
      <el-button @click="dialogFormCoveVisible = false">取 消</el-button>
      <el-button :plain="true" type="primary" @click="handleOk">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, watch, ref } from 'vue'
import type { TradeMArk } from '@/api/product/trademark/type'
import { UploadProps, ElMessage } from 'element-plus'
//定义收集品牌
let trademarkParams = reactive<TradeMArk>({
  tmName: '',
  logoUrl: '',
  updateTime: new Date().toLocaleString('zh-CN'),
})
const props = defineProps({
  dialogFormVisible: {
    type: Boolean,
    default: false,
  },
  currTradeMark: {
    type: Object,
    default: {},
  },
  titleActive: {
    type: String,
  },
  handleSubmit: {
    type: Function,
    required: true,
  },
})
//获取el-form组件实例
let formRef = ref()
//品牌自定义表单校验规则
//@ts-ignore
const validatorTmName = (rule: any, value: any, callback: any) => {
  //当表单元素触发blur时候,会触发此方法
  //自定义表单校验规则
  if (value.trim().length >= 2) {
    callback()
  } else {
    //校验未通过返回的错误的提示信息
    callback(new Error('品牌名称位数大于等于两位'))
  }
}
//品牌logo图片自定义验证
//@ts-ignore
const validatorlogoUrl = (rule: any, value: any, callback: any) => {
  //value 就是图片上产到目标服务器返回的logoUrl
  // console.log("图片校验",rule+'%%'+value+'%%'+callBack);
  if (value.length) {
    callback()
  } else {
    //校验未通过返回的错误的提示信息
    callback(new Error('图片logo务必要上传!'))
  }
}
//表单校验规则对象
const rules = {
  tmName: [
    //required 说明这个字段是必须的,表单前会出现五角星
    //trigger: 表示触发校验规则的时机 [blur,change]
    { required: true, trigger: 'blur', validator: validatorTmName },
  ],
  logoUrl: [
    {
      required: true,
      validator: validatorlogoUrl,
    },
  ],
}
watch(
  () => props.currTradeMark,
  (newvalue) => {
    trademarkParams.tmName = newvalue.tmName
    trademarkParams.logoUrl = newvalue.logoUrl
    trademarkParams.id = newvalue.id
    // trademarkParams={...newvalue}
    console.log('修改', newvalue)
  },
)
const emits = defineEmits(['update:modelValue'])
const dialogFormCoveVisible = computed({
  get: () => {
    return props.dialogFormVisible
  },
  set: (value) => {
    emits('update:modelValue', value)
    //清空收集的tradeMark数据
    trademarkParams.tmName = ''
    trademarkParams.logoUrl = ''
    trademarkParams.updateTime = ''
  },
})

//品牌弹窗初次加载时清除表单验证信息
const clearFormVallidate = () => {
  //清除品牌名称
  formRef.value.clearValidate('tmName')
  //清除品牌logo
  formRef.value.clearValidate('logoUrl')
}
defineExpose({
  clearFormVallidate,
})
//上传图片组件-->上传图片之前触发的的钩子函数 用来限制图片大小等提示信息
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //上传图片成功之前触发,上传文件之前可以用来约束文件的类型和大小
  //上传文件的类型:png|jpg|gif 4M
  if (
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小应小于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式务必是PNG|JPG|GIF',
    })
    return false
  }
}

//图片上传成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  // response 即为当前这次图片上传post请求服务器返回的数据
  //收集图片的地址将来添加图片的时候将参数传递给服务器
  // console.log("response",response,uploadFile);
  trademarkParams.logoUrl = response.data
  //   imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  //图片上传成功,清除掉的对应放入图片校验结果
  formRef.value.clearValidate('logoUrl')
}
const handleOk = async () => {
  //再点击确定确定按钮发请求之前,要对整个表单进行校验
  await formRef.value.validate()

  props.handleSubmit(trademarkParams)
}
</script>

<style lang="scss" scoped>
avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
